import { getZone, getPersonalInfoFull, updateZone } from '../../../api/user'
import { findColumnList } from '../../../api/base'

Page({
  data: {
    title: '',
    name: '',
    subName: '',
    content: '',
    labels: [],
    show: false,
    tagList: [],
    personalInfo: {}
  },
  onLoad: function (options) {
    this.setData({
      title: options.title,
      name: options.name,
      subName: options.subName
    })
    this.init()
  },
  async init() {
    getZone().then(res => {
      this.setData({
        content: res[this.data.name],
        labels: res[this.data.subName],
        personalInfo: res
      })
    })
    await getPersonalInfoFull().then(res => {
      let stageList = []
      let subjectList = []
      const labels = this.data.labels
      res.phase.forEach(p => {
        stageList.push(p.itemCode)
      })
      res.subjects.forEach(s => {
        subjectList.push(s.subjectId)
      })
      findColumnList({
        stageList: stageList,
        subjectList: subjectList
      }).then(fres => {
        fres.forEach(tag => {
          tag.isCheck = false;
          if (tag.sub && tag.sub.length) {
            tag.sub.forEach(s => {
              s.isCheck = false
            })
          }
        })
        fres.forEach(tag => {
          labels.forEach(l => {
            if (tag.tagsId === l.tagsId) {
              tag.isCheck = true
            }
          })
        })
        this.setData({
          tagList: JSON.parse(JSON.stringify(fres))
        })
      })
    })
  },
  editContent(e) {
    this.setData({
      content: e.detail.value
    })
  },

  selectLabels() {
    this.setData({show: true})
  },

  cancelSelect() {
    this.setData({show: false})
  },

  checkTag(e) {
    const item = e.currentTarget.dataset.item
    const index = e.currentTarget.dataset.index
    item.isCheck = !item.isCheck
    this.data.tagList[index].isCheck = item.isCheck
    this.setData({
      tagList: this.data.tagList
    })
  },

  confirmSelect() {
    this.data.labels = []
    this.data.tagList.forEach(tag => {
      if (tag.isCheck) {
        this.data.labels.push(tag)
      }
    })
    this.setData({
      show: false,
      labels: this.data.labels
    })
  },

  done() {
    let personalInfo = this.data.personalInfo
    personalInfo[this.data.name] = this.data.content
    personalInfo[this.data.subName] = this.data.labels
    this.setData({
      personalInfo: personalInfo
    })
    const pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];
    updateZone(this.data.personalInfo).then(res => {
      wx.navigateBack({
        delta: 1,
        success(res) {
          prevPage.init()
        }
      })
    })
  }
})
